﻿using System;
using System.Web;
using ZX.DBModule;
using ZX.EHR.Library;
using System.IO;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using System.Reflection;

namespace ZX.Web.UI.Controls
{
    public partial class UploadFile : ZX.Web.UI.Controls.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.GetStringFromQueryString("action", "") == "upload")
            {
                string[] filext = { "exe", "dll", "aspx", "asp", "jar", "com", "bat", "php", "jsp" };
                HttpPostedFile postfile = ZXContext.Request.Files[0];
                Response.Clear();
                if (Request.Files.Count > 0 && !ZX.Common.Globals.IIFExistExtension(postfile.FileName, filext))
                {
                    string output = "";// @"<script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction({0} ,'{1}');</script>";
                    // System.Web.HttpPostedFile f = Request.Files["upload"];
                    if (this.EntityName == "V_hrCandidate")
                    {
                        SavePersonResume(postfile.FileName, (postfile.ContentLength / 1024).ToString() + "k","", postfile);
                    }
                    if (this.EntityName == "Product")
                    {
                        SaveProductPicture(postfile.FileName, (postfile.ContentLength / 1024).ToString() + "k", postfile);
                    }
                    output = "";// string.Format(output, Request["CKEditorFuncNum"], filename);
                    Response.Write(output);
                    Response.End();
                }
            }
            else
            {
                if (!IsPostBack)
                {
                   this.FlashUpload1.QueryParameters = "action=upload&entity="+GetStringFromQueryString("entity","")+"&id=" + this.GetStringFromQueryString("id", "");
                }
                //Response.End();
            }
        }

        void SavePersonResume(string FileName, string Size, string FilePath, HttpPostedFile postfile)
        {
            string filename = "/Upload/Person/Resume/" + System.Guid.NewGuid().ToString() + postfile.FileName.Substring(postfile.FileName.LastIndexOf("."));
            postfile.SaveAs(Server.MapPath("~" + filename));
            //string strResumeSource = "";
            FileInfo fileInfo = new FileInfo(Server.MapPath("~" + filename));
            string resFileName = Server.MapPath("~" + filename);//Request.PhysicalApplicationPath + "EHR/ResumeFiles/" + strResumeSource + "/" + fileInfo.Name;
            //uploadedFile.SaveAs(resFileName);
            //解析简历
            IdentifyEncoding getEncoding = new IdentifyEncoding();
            System.Text.Encoding encoding = getEncoding.GetEncoding(getEncoding.GetEncodingName(new FileInfo(resFileName)));
            StreamReader reader = new StreamReader(resFileName, encoding);
            string content = reader.ReadToEnd().Replace("<div><a href=\"http://WizBrother.com\">http://www.WizBrother.com/</a></div>","");
            reader.Close();
            try
            {
               // object o = System.Configuration.GetSection("resumeSourceConfig");
               //  ResumeSourceTypesConfig config = o as ResumeSourceTypesConfig;

                ResumeParsedInfo resume = null;
                string[] _str = "ZhiLianZhaoPin,Cjol,51job,ChinaHR".Split(',');
                    foreach (var str in _str)
                    {  
                        try
                        {
                            resume = ParseTools.ExecuteParse(str/*strResumeSource*/, content);
                            if (resume != null)
                            {
                                break;
                            }
                        }
                        catch
                        {

                        }
                    }
            
            
                if (resume == null)
                {
                    return;
                }
                //if (resume != null)
                //{
                //if (listResumes == null) listResumes = new List<ResumeParsedInfo>();
                //if (listContent == null) listContent = new List<string>();
                //listResumes.Add(resume);
                string tempEncodingStr = "<" + encoding.WebName + ">\r\n";//加入编码
                content = (tempEncodingStr + content);
                //}
                //ResumeParsedInfo listResumes = new ResumeParsedInfo();
                //RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);

                string fileLabel = fileInfo.Name;
                string fileLength = postfile.ContentLength / 1024 + "K";
                //return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
                hrCandidate instance = null;
                ZX.BLL.Extend.BaseBussnies hrCandidateBll = null;

                instance = ZX.Common.Globals.getEntity("hrCandidate") as hrCandidate;
                instance.RequirementID = Guid.Empty;// new Guid(requirementID);
                instance.ResumeHTML = Server.HtmlEncode(content);
                instance.AddUser = this.User.UserID;
                instance.AddTime = DateTime.Now;
                instance.Name = resume.Name;
                instance.Gender = resume.Gender;
                instance.IDCardNo = resume.IDCardNO;
                instance.PhoneNO = resume.PhoneNO;
                instance.Email = resume.Email;
                instance.Degree = resume.Degree;
                instance.PostID = GetGuidFromQueryString("id");
                instance.ResumeFileName = filename;
                if (resume.BirthDay != string.Empty)
                {
                    try
                    {
                        instance.BirthDay = DateTime.Parse(resume.BirthDay);
                    }
                    catch { }
                }
                instance.NowPosition = resume.NowPosition;
                instance.WorkYears = resume.WorkYears;
                instance.ID = Guid.NewGuid();
                hrCandidateBll = new ZX.BLL.Extend.BaseBussnies(instance);
                hrCandidateBll.Insert(); HttpContext.Current.Response.Write("0");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("1");
                //throw ex;
            }
            finally
            {
                //listResumes.Clear();
                //listContent.Clear();
            }

        }

        void SaveProductPicture(string FileName, string Size,  HttpPostedFile postfile)
        {
            string filename = "/Upload/Person/Resume/" + System.Guid.NewGuid().ToString() + postfile.FileName.Substring(postfile.FileName.LastIndexOf("."));
            postfile.SaveAs(Server.MapPath("~" + filename));
            string _productID = this.GetStringFromQueryString("id", "");
            string FilePath = filename;

            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = "siteProductPicture";
            string[] strKeyArrary = instance.GetKey();
            if (strKeyArrary != null)
            {
                instance.TableKey = strKeyArrary[0];
                instance.KeyType = strKeyArrary[1];
            }
            instance.CreateDT();
            //string[] s1 = { "[@@@]" };
            //string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson ="{"+ string.Format("\"ID\":\"\",\"ProductID\":\"{4}\",\"Size\":\"{0}\",\"FileName\":\"{1}\",\"FilePath\":\"{2}\",\"Picture\":\"{3}\",\"AddUser\":\"\",\"AddTime\":\"\"", Size, FileName, FilePath, FileName, _productID)+"}";//json;// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = ZX.Common.Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("AddUser"))
            {
                instance.FieldValue["AddUser"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("AddTime"))
            {
                instance.FieldValue["AddTime"] = System.DateTime.Now;
            }
            instance.SetValue(instance.FieldValue);
            this._bll.entity = instance;
            _bll.Insert();// _bll.GetSqlCommand(instance);
        }
    }
}